package top.qitun.tian.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import top.qitun.bizz.user.tuser.entity.TUserBO;
import top.qitun.model.response.ObjectDataResponse;
import top.qitun.model.security.AuthenticationDTO;
import top.qitun.tian.api.UserManagementServiceAPI;
import top.qitun.tian.util.JsonWebTokenUtility;

@RestController
@RequestMapping("/auth")
public class AuthenticationController {

	Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private UserManagementServiceAPI userManagementServiceAPI;
	
//	@Autowired
//	private ClientServiceAPI clientServiceAPI;
	
	/**
     * Token工具类
     */
//    @Autowired
//    private TokenUtil tokenUtil;
	/**
     * 权限管理
     */
    @Autowired
    private AuthenticationManager authenticationManager;
    
	
//	@Autowired
//	private AccountServiceV1 accountServiceV1;
    
    /**
     * Create authentication token map.
     *
     * @param version  the version
     * @param username the username
     * @param password the password
     * @return the map
     */
    @PostMapping(value = "/token", produces = "application/json; charset=UTF-8")
    @ApiOperation(value = "获取token")
    public ObjectDataResponse<TUserBO> createAuthenticationToken(@RequestBody AuthenticationDTO authenticationDTO) {

        //完成授权
        final Authentication authentication = authenticationManager.authenticate(
            new UsernamePasswordAuthenticationToken(authenticationDTO.getMobile(), authenticationDTO.getPassword())
        );
        SecurityContextHolder.getContext().setAuthentication(authentication);

        final UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        TUserBO userDTO = new TUserBO(userDetails.getUsername(),userDetails.getPassword());
        userDTO.setExpirationDate(new Date(System.currentTimeMillis()+36000*1000L));
        final String token = JsonWebTokenUtility.createJsonWebToken(userDTO); //生成Token

        Map<String, Object> tokenMap = new HashMap<>();
//        tokenMap.put("access_token", token);
//        tokenMap.put("expires_in", tokenUtil.getExpiration());
//        tokenMap.put("token_type", TokenUtil.TOKEN_TYPE_BEARER);
       
        userDTO.setToken(token);
        return new ObjectDataResponse<TUserBO>(0, "授权成功!", userDTO);
    }

//	@RequestMapping(value = "/user/login", method = RequestMethod.POST)
//	public ObjectDataResponse<TUserBO> authenticate(@RequestBody AuthenticationDTO authenticationDTO) {
//		// Authenticate the user
//		ObjectDataResponse<TUserBO> response = userManagementServiceAPI.authenticateUser(authenticationDTO);
//		if (response.getCode() == 0) {
//			TUserBO user = response.getData();
//			// Build the AuthTokenDetailsDTO
//			user.setExpirationDate(buildExpirationDate());
//			// Create auth token
//			String jwt = JsonWebTokenUtility.createJsonWebToken(user);
//			if (jwt != null) {
//				user.setToken(jwt);
//			}
//		}
//		return response;
//	}
	
	
//	@RequestMapping(value = "/client/login", method = RequestMethod.POST)
//	public ObjectDataResponse<ClientBO> clientlogin(@RequestBody AuthenticationDTO authenticationDTO) {
//		// Authenticate the user
//		try {
//			ObjectDataResponse<ClientBO> response = clientServiceAPI.clientlogin(authenticationDTO);
//			if (response.getCode() == 0) {
//				ClientBO user = response.getData();
//				if(user==null){
//					return new ObjectDataResponse<ClientBO>(1, "用户不存在");
//				}
//				// Build the AuthTokenDetailsDTO
//				user.setExpirationDate(buildExpirationDate());
//				// Create auth token
//				String jwt = JsonWebTokenUtility.createJsonWebToken(user);
//				if (jwt != null) {
//					user.setToken(jwt);
//				}
//			}
//			return response;
//		} catch (Exception e) {
//			logger.error("系统错误", e);
//			return new ObjectDataResponse<ClientBO>(-1, "系统错误,联系管理员");
//		}
//	}

//	@RequestMapping(value = "/client/register", method = RequestMethod.POST)
//	public RegisterResponse<ClientBO> clientRegister(@RequestBody ClientRegisterRequest registerRequest) {
//		// Authenticate the user
//		ObjectDataResponse<ClientBO> respose = clientServiceAPI.register(registerRequest);
//		if (respose.getCode() != 0) {
//			return new RegisterResponse<>(respose.getCode(), respose.getMessage());
//		} else {
//			ClientBO user = respose.getData();
//			user.setExpirationDate(buildExpirationDate());
//			// Create auth token
//			String jwt = JsonWebTokenUtility.createJsonWebToken(user);
//			if (jwt != null) {
//				user.setToken(jwt);
//			}
//
//			return new RegisterResponse<ClientBO>(0, "注册成功", user);
//		}
//		// If authentication fails, return an unauthorized error code
//	}

	
//	private Date buildExpirationDate() {
//		Calendar calendar = Calendar.getInstance();
//		calendar.add(Calendar.HOUR_OF_DAY, 1);
//		Date expirationDate = calendar.getTime();
//		return expirationDate;
//	}
	
//	@RequestMapping(path = "/accounts")
//	public Object getUserAccount() throws Exception {
//		Object object = accountServiceV1.getUserAccounts();
//		return object;
//	}
}
